<template>
  <div class="goods-image">
    <!-- middle之前放置大图盒子 -->
    <div
      v-show="!isOutside"
      class="large"
      :style="[
        {
          backgroundImage: `url(${image[currIndex]})`,
          backgroundPosition: `${large.left}px ${large.top}px`,
        },
      ]"
    ></div>
    <div class="middle" ref="target">
      <img :src="image[currIndex]" alt="" />
      <!-- 蒙层容器 -->
      <div
        v-show="!isOutside"
        class="layer"
        :style="{ left: `${pos.left}px`, top: `${pos.top}px` }"
      ></div>
    </div>
    <ul class="small">
      <li v-for="(img, i) in image" :key="i" @mouseenter="currIndex = i">
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  setup () {
    const currIndex = ref(0)
    const target = ref(null)
    // 三个参数都是ref对象!!!!!!!! ===>要用值做判断和修改 都要.value!!!!!
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // 定义放大图片位置
    const large = ref({ left: 0, top: 0 })
    //  定义蒙层位移
    const pos = ref({ left: 0, top: 0 })
    // watch ===> elementX and elementY
    watch([elementX, elementY], () => {
      // 判断蒙层左右距离
      if (elementX.value < 100) {
        // 蒙层不能向盒子外溢出
        pos.value.left = 0
      } else if (elementX.value > 300) {
        pos.value.left = 200
      } else {
        pos.value.left = elementX.value - 100 // 侦听的值也要改变赋值必须得加.value 让鼠标在蒙层中心点
      }
      // 判断蒙层上下距离
      if (elementY.value < 100) {
        // 蒙层不能向盒子外溢出
        pos.value.top = 0
      } else if (elementY.value > 300) {
        pos.value.top = 200
      } else {
        pos.value.top = elementY.value - 100
      }
      // 监听放大图
      large.value.left = -pos.value.left * 2
      large.value.top = -pos.value.top * 2
    })

    return { currIndex, target, isOutside, pos, large }
  },
  props: {
    image: {
      type: Array,
      default: () => []
    }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
